package Tools;


import JDBCPre.User;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用反射封装完全解耦的Crud
 */
@SuppressWarnings("all")
public class Db_Crud {
//Class<?>

    /**
     * 实现表中所有数据的查询
     *
     * @param sql 查询sql语句  select * from stu where name="xxx"
     * @param c   反射的实体类对象
     * @param <T> 任意合法的对象类型
     * @return ArrayList
     */
    public <T> List<T> selectData(String sql, Class<T> c) {
        //保存查询的数据
        ArrayList<T> list = new ArrayList<>();
        //链接数据库
        try {
            Connection connection = JDBCUtils.getConnection();
            PreparedStatement preStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preStatement.executeQuery(sql);
            ResultSetMetaData metaData = resultSet.getMetaData();
            // System.out.println("metaData = " + metaData.getColumnName(1));//??
            //System.out.println("metaData.getColumnCount() = " + metaData.getColumnCount());
            while (resultSet.next()) {
                T t = c.newInstance();
                for (int i = 1; i <= metaData.getColumnCount(); i++) {
                    Object val = resultSet.getObject(i);//获取每一列的数据
//                    System.out.println("val = " + val);
                    String columnName = metaData.getColumnName(i);
                    //代码执行中，通过反射动态的重新构建了字段对象
                    Field declaredField = c.getDeclaredField(columnName);
                    declaredField.setAccessible(true);
                    declaredField.set(t, val);
                }
                list.add(t);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return list;
    }

    public static void main(String[] args) {
        Db_Crud db_crud = new Db_Crud();
        List<User> emps = db_crud.selectData("select * from User", User.class);
        for (User o : emps) {
            System.out.println("o = " + o);
        }
    }
}